<script lang="ts" setup>
import { reactive } from 'vue';

import { QTableSearchProps } from '@/components/q-table-search/type';
import PageTable from '@/components/q-table/component/page-table.vue';
import { usePageTable } from '@/hooks';
import { EditMenuParams, IMenu, api } from '@/service';
import { truncate } from 'fs';
import type { VxeColumnSlotTypes, VxeGridProps } from 'vxe-table';

const tableRow = ref<IMenu>();

const { message, dialog } = useFeedback(['message', 'dialog']);

const menuStore = useMenuStoreHook();

const { pageTableRef, columns, operations, tableRequest, refreshTable, getTableInstance } = usePageTable<IMenu>({
	api: (params) => api.menu.getAllMenu(params.query),
	columns: [
		{ field: 'sort', title: '排序', treeNode: true },
		{ field: 'name', title: '名称', searchFormItem: { type: 'n-input' } },
		{ field: 'menu_id', title: '标识', searchFormItem: { type: 'n-input' } },
		{ field: 'url', title: 'URL' },
		{
			field: 'enable',
			title: '是否启用',
			cellRender: {
				name: 'Switch',
				props: ({ row }: VxeColumnSlotTypes.DefaultSlotParams<IMenu>) => ({
					onUpdateValue: handleSwitchMenuEnable,
					disabled: row.menu_id === 'system_menu',
				}),
			},
		},
	],
	operations: [
		{ label: '新增', key: 'add', show: (row) => !row.parent_id && row.url !== '/' },
		{ label: '编辑', key: 'edit' },
		{ label: '删除', type: 'error', key: 'delete' },
	],
});

const treeConfig = ref<VxeGridProps['treeConfig']>({
	transform: true,
	rowField: 'menu_id',
	childrenField: 'children',
	parentField: 'parent_id',
	expandAll: true,
});

const { formItems, handleAdd, handleEdit, setFormItem } = useUpset<EditMenuParams, string>({
	formItems: [
		{
			field: 'menu_id',
			title: '标识',
			type: 'n-input',
			info: '请输入菜单项的ID，不可重复',
			validate: [{ required: true, message: '请输入菜单项的ID' }],
		},
		{ field: 'name', title: '名称', type: 'n-input', validate: [{ required: true, message: '请输入菜单项的名称' }] },
		{
			field: 'url',
			title: 'URL',
			info: 'URL必须是/开头，若URL为空代表是目录而不是叶子节点',
			type: 'n-input',
		},
		{
			field: 'sort',
			title: '序号',
			info: '请输入菜单序号（越大越靠后）',
			type: 'n-input-number',
			class: 'w-full',
			validate: [{ required: true, message: '请输入菜单项的序号' }],
		},
		{
			field: 'parent_id',
			title: '父级菜单',
			info: '新增菜单时自动填充, 一级菜单不需要填写',
			type: 'data-select',
			ucloudDb: {
				collection: 'opendb-admin-menus',
				field: 'menu_id as value,name as label',
				where: 'url==""',
			},
		},
		{
			field: 'permission',
			title: '权限',
			info: '当用户拥有以上被选中的权限时，可以访问此菜单。建议仅对子菜单配置权限，父菜单会自动包含。如不选择权限，意味着仅超级管理员可访问本菜单',
			type: 'data-checkbox',
			ucloudDb: {
				collection: 'uni-id-permissions',
				field: 'permission_id as value,permission_name as label',
			},
		},
		{ field: 'enable', title: '是否启用', type: 'n-switch' },
	],
	title: '菜单',
	modalOptions: {
		class: 'w-[600px]',
	},
	api: (data) => {
		return tableRow.value ? api.menu.updateMenu({ ...data, _id: tableRow.value._id }) : api.menu.addMenu(data);
	},
	success: () => {
		refreshTable({ expand: true });
		menuStore.getMenuList();
	},
});

const handleAddMenu = (params?: { isTop?: boolean; row?: IMenu }) => {
	if (params?.isTop) {
		const index = formItems.value.findIndex((item) => item.field === 'parent_id');
		if (index !== -1) {
			formItems.value[index] = {
				...formItems.value[index],
				type: 'n-select',
				props: {
					disabled: true,
				},
			};
		}
	}

	handleAdd({
		initialData: {
			parent_id: params?.row?.menu_id,
		},
	});
};

const handleEditMenu = (row: IMenu) => {
	tableRow.value = row;
	handleEdit({
		initialData: row,
	});
};

async function handleSwitchMenuEnable(value: boolean, params: VxeColumnSlotTypes.DefaultSlotParams<IMenu>) {
	const enableDialog = dialog.warning({
		title: params.row.enable ? '禁用菜单' : '启用菜单',
		content: params.row.enable ? '确定禁用该菜单吗？' : '确定启用该菜单吗？',
		positiveText: '确定',
		negativeText: '取消',
		onPositiveClick: async () => {
			try {
				enableDialog.loading = true;
				const res = await api.menu.switchMenuEnable({ id: params.row._id, enable: !params.row.enable });
				menuStore.getMenuList();
				if (res.updated) {
					message.success('操作成功');
					params.row.enable = value;
				}
			} catch (error) {
				console.log(error);
			} finally {
				enableDialog.loading = false;
			}
		},
	});
}

const handleSelect = (params: { key: string; row: IMenu }) => {
	switch (params.key) {
		case 'add':
			handleAddMenu({ isTop: true, row: params.row });
			break;
		case 'edit':
			handleEditMenu(params.row);
			break;
		case 'delete':
			break;
	}
};

const handleRequested = () => {
	pageTableRef.value?.getTableInstance()?.setAllTreeExpand(true);
};
</script>
<template>
	<page-wrap>
		<page-table
			ref="pageTableRef"
			:show-pager="false"
			:tree-config="treeConfig"
			:columns="columns"
			:operations="operations"
			:request="tableRequest"
			@requested="handleRequested"
			@operation-select="handleSelect"
		>
			<template #toolbarButtons>
				<div class="flex justify-end space-x-2">
					<n-button type="primary" @click="() => handleAddMenu({ isTop: true })">新增菜单</n-button>
				</div>
			</template>
		</page-table>
	</page-wrap>
</template>
